package org.alex.sample.service.Impl;

import java.util.ArrayList;
import java.util.List;

import org.alex.sample.dao.IUserDAO;
import org.alex.sample.dao.SubjectDAO;
import org.alex.sample.model.ExamUserRole;
import org.alex.sample.model.ExamUserSubject;
import org.alex.sample.model.Subject;
import org.alex.sample.model.User;
import org.alex.sample.page.PagerModel;
import org.alex.sample.service.SubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SubjectServiceImple implements SubjectService {
	
	@Autowired
	private SubjectDAO subjectDao;
	
	@Autowired
	private IUserDAO userDao;

	@Override
	public List<Subject> findAllSubject() throws Exception {
		return subjectDao.findAllSubject();
	}

	@Override
	public void createSubject(Subject subject) throws Exception {
		subjectDao.createSubject(subject);
	}

	@Override
	public void editSubject(Subject subject) throws Exception {
		subjectDao.editSubject(subject);
	}

	@Override
	public void deleteSubject(Integer sub_id) throws Exception {
		subjectDao.deleteSubject(sub_id);
	}

	@Override
	public Subject findSubjectById(Integer sub_id) throws Exception {
		return subjectDao.findSubjectById(sub_id);
	}
	
	public PagerModel<Subject> findAllByPage() throws Exception{
		return subjectDao.findAllByPage();
	}

	//查找全部学生
	@Override
	public List<User> getAllUser() throws Exception {
		List<User> userList = userDao.findAllUser();
		return userList;
	}

	//查找科目关联的全部学生
	@Override
	public List<String> getSubjectUser(Integer subjectId) throws Exception {
		List<String> userIdList = subjectDao.getSubjectUser(subjectId);
		return userIdList;
	}
	
	public void saveSubjectUser(List<String> checkedUserId, Integer subjectId) throws Exception {
		//获取该科目关联的全部学生
		List<String> userIdList = this.getSubjectUser(subjectId);
		//保存新勾选的的学生ID
		List<String> insertList = new ArrayList<String>();
		//保存去掉勾选的学生ID
		List<String> deleteList = new ArrayList<String>();
		
		//判断哪些学生是新增的
		for(String selectUser : checkedUserId) {
			if(!userIdList.contains(selectUser)) {
				insertList.add(selectUser);
			}
		}
		
		//判断哪些学生是去掉勾选的
		for(String selectUser :userIdList) {
			if(!checkedUserId.contains(selectUser)) {
				deleteList.add(selectUser);
			}
		}
		subjectDao.insertSubjectUser(insertList, subjectId);
		subjectDao.deleteSubjectUser(deleteList, subjectId);
	}


}
